<?php
namespace Modules\User\Controllers;

class WalletController extends \Phalcon\Mvc\Controller {
	public function initialize() {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
	}

	public function rechargeAction() {
		$validation = $this -> user::getWalletValidationInstance()
		-> addType()
		-> addAccount()
		-> addAmount()
		-> addActive()
		-> execute($this -> request -> getPost());
		if($validation['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$validation['code'],'msg'=>$validation['message']]);
		}

		$filter = $this -> user::getWalletFilterInstance()
		-> setData($validation['data'])
		-> addType()
		-> addAccount()
		-> addAmount()
		-> addActive()
		-> execute();
		if($filter['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$filter['code'],'msg'=>$filter['message']]);
		}

		$this -> db -> begin();
		try {
			$service = $this -> user::getWalletServiceInstance() -> updateAmount($filter['data']);
			if($service['code'] != 0) {
				throw new \Exception($service['message']);
				//throw new \Exception('充值失败');
			}
			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'充值成功', 'data' => $filter['data']]);
	}
}